#!/bin/bash

# 设置脚本在发生错误时停止执行
set -e

# 输出日志函数
log() {
    echo "$(date +'%Y-%m-%d %H:%M:%S') - INFO - $1"
}

# 错误处理函数
error() {
    echo "$(date +'%Y-%m-%d %H:%M:%S') - ERROR - $1"
    exit 1
}

# 创建 Nginx deployment
log "Creating Nginx deployment..."
kubectl create deployment nginx --image=nginx
if [ $? -ne 0 ]; then
    error "Failed to create Nginx deployment."
fi
log "Nginx deployment created successfully."

# 开放 80 端口，创建 NodePort 类型的 Service
log "Exposing Nginx deployment on port 80 with NodePort..."
kubectl expose deployment nginx --port=80 --type=NodePort
if [ $? -ne 0 ]; then
    error "Failed to expose Nginx deployment."
fi
log "Nginx exposed successfully."

# 查看 Pod 状态，等待 Pod 完全启动
log "Checking Nginx pod status..."
kubectl get pod
if [ $? -ne 0 ]; then
    error "Failed to copy files to Nginx container."
fi
log "Files copied to Nginx container successfully."


log "Nginx pod is running."

read   -p "输入nginxID:例如(nginx-77b4fdf86c-cvx86)"  NGINX_POD_NAME 

# 将解压后的文件复制到 Nginx 容器的站点目录
log "Copying files to Nginx container..."
kubectl cp choujiang "$NGINX_POD_NAME":/usr/share/nginx/html
if [ $? -ne 0 ]; then
    error "Failed to copy files to Nginx container."
fi
log "Files copied to Nginx container successfully."

# 进入容器执行操作
log "Executing commands inside Nginx container..."
kubectl exec -it "$NGINX_POD_NAME" -- /bin/bash -c "cd /usr/share/nginx/html/ && mv choujiang/* . && ls"
if [ $? -ne 0 ]; then
    error "Failed to execute commands inside Nginx container."
fi
log "Commands executed inside Nginx container successfully."

# 查看 Service 状态
log "Checking service status..."
kubectl get service
if [ $? -ne 0 ]; then
    error "Failed to get service status."
fi
log "Service status checked successfully."

log "All tasks completed successfully."